package com.hw01.service.impl;

import com.hw01.config.MyBatisSqlSessionFactory;
import com.hw01.entity.User;
import com.hw01.exception.DataNotFoundException;
import com.hw01.exception.LoginException;
import com.hw01.mapper.UserMapper;
import com.hw01.service.UserService;
import com.hw01.utils.TokenUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author Kx
 * @Date 2025/5/13 8:22
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    /**
     * @author: kx
     * @date: 2025/5/13 8:33
     * @return java.util.List<com.entity.User>
     * @description: 查询用户所有信息
    */
    @Override
    public List<User> findAllUser() {
        // 获取SqlSession会话
        try (SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession()) {
            // 获取UserMapper接口
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            // 判断是否查询到数据
            if (mapper.findAllUser() != null) {
                return mapper.findAllUser();
            }
            throw new DataNotFoundException(100, "用户信息不存在");
        }
    }

    /**
     * @author: kx
     * @date: 2025/5/13 19:50
     * @param account : 账号
     * @param password : 密码
     * @return com.entity.User
     * @description:
    */
    @Override
    public String login(String account, String password) {
        // 获取SqlSession会话
        try (SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession()) {
            // 获取UserMapper接口
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            // 判断是否查询到数据
            User user = mapper.login(account, password);
            if (user != null) {
                // 生成令牌
                return TokenUtils.createToken(user.getId());
            }
            throw new LoginException(101, "账号或密码错误");
        }
    }
}
